/* $RCSFile: SiteSettings.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/SiteSettings/SiteSettings.ascx.cs $
 * $log$
 * Revision 27 2011/02/22 01:23:08  christian.surieux
 *   V4 Migration 22/2/11
 * Revision 27 2011/02/22 01:22:08  christian.surieux
 *   V4 Migration 22/2/11
 * Revision 20 2010/08/09 10:51:22  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:44:00  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:26  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Globalization;

using AddonNice.Design;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.Configuration;
using AddonNice.Diagnostics;
using AddonNice.Helpers;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.SiteSettings
{
	/// <summary>
	/// This class manage the portals parameters
	/// It reads settings from db and store them when modified
	/// </summary>
	public partial class SiteSettings : PortalModuleControl 
	{
		PortalsDB PDB           =   new PortalsDB();
		bool    ShouldRedirect  =   false;		// indicator used on update to detect a necessary redirect
		/// <summary>
		/// Admin Module
		/// </summary>
		public override bool AdminModule
		{
			get
			{
				return true;
			}
		}

		public override Guid GuidID 
		{
			get
			{
				return new Guid(StStr.SiteSettingsGuid);
			}
		}



		int PortalType
		{
			get
			{
				return (int)ViewState[StStr.DBPortalType];
			}
			set
			{
				ViewState[StStr.DBPortalType] = value;
			}
		}


		/// <summary>
		/// The Page_Load server event handler on this user control is used
		/// to populate the current site settings from the config system
		/// </summary>
		private void Page_Load(object sender, System.EventArgs e)
		{
			if (ModuleTraceSwitch.Sw.TraceVerbose)
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]SiteSettings Page_Load IsPostBack : {0}", IsPostBack),ModuleTraceSwitch.Sw.Info);
			AddAjaxSetting(updateBtn,siteName);
			AddAjaxSetting(updateBtn,sitePath);
			//AddAjaxSetting(updateBtn,TbCrmServer);
			//AddAjaxSetting(updateBtn,TbCrmOrganization);
			AddAjaxSetting(updateBtn,EditTable);
			// If this is the first visit to the page, populate the site data
			if ( !IsPostBack )
			{
				/*
				// We flush cache for enable correct localization of items
				PortalSettings.FlushAllPortalSettingsCache();
				try
				{
					siteName.Text           =   portalSettings.PortalName;
					sitePath.Text           =   portalSettings.PortalPath;
					TbCrmServer.Text        =   portalSettings.CrmServer.DiscoServer;
					TbCrmOrganization.Text  =   portalSettings.CrmServer.Organization;
					PortalType              =   (int)portalSettings.PortalType;
					EditTable.DataBind();
				}
				catch (Exception ex)
				{
					if (ModuleTraceSwitch.Sw.TraceError)
						Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]SiteSettings Page_Load ex : {0}", ex),ModuleTraceSwitch.Sw.Info);
				}
				 * */
			}
		}
				

		/// <summary>
		/// Triggered by the update or update and save buttons
		/// Is used to update the Site Settings within the Portal Config System
		/// </summary>
		void SiteSettings_ADNUpdateModule(object sender, ModuleEventArgs e)
		{
			if (ModuleTraceSwitch.Sw.TraceVerbose)
				Trace2.WriteLine( "[V]SiteSettings SiteSettings_ADNUpdateModule BEG.",ModuleTraceSwitch.Sw.Info);
			
			//Update main settings and Tab info in the database
			try
			{
				PDB.UpdatePortal2(portalSettings.PortalID, siteName.Text.Trim(),sitePath.Text.Trim(),PortalType);
				// Update custom settings in the database, set the redirect indicator
				ShouldRedirect  =   false;
				EditTable.UpdateControls();
			}
			catch (Exception ex)
			{
				if (ModuleTraceSwitch.Sw.TraceError)
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"SiteSettings SiteSettings_ADNUpdateModule ex : {0}", ex),ModuleTraceSwitch.Sw.Info);
				throw;
			}
			if (ModuleTraceSwitch.Sw.TraceVerbose)
				Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture, "[V]SiteSettings SiteSettings_ADNUpdateModule END ShouldRedirect: {0}", ShouldRedirect), ModuleTraceSwitch.Sw.Info);
			// Redirect to this site to refresh
			if (ShouldRedirect)
			{
				e.Redirect      =   true;
				e.RedirectUrl   =   Request.RawUrl;
			}
			else portalSettings.ReloadPortal(true);
		}

		/// <summary>
		/// When MasterPage or Theme has changed, we must force a real postbak on the page to show the changes
		/// </summary>
		private void EditTable_UpdateControl(object sender, AddonNice.Configuration.SettingsTableItemEventArgs e)
		{
			try
			{
				string key  =   e.CurrentItem.EditControl.ID;
				string val  =   e.CurrentItem.Value;
				switch (key)
				{
					case StStr.SiteMasterPageFile:
						if ( ADNPage.MasterPageFile != val )
							ShouldRedirect = true;
						break;
					case StStr.SiteTheme2:
						if ( ADNPage.Theme != val )
							ShouldRedirect = true;
						break;
				}

				if (ModuleTraceSwitch.Sw.TraceVerbose)
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]SiteSettings EditTable_UpdateControl key: {0}, val: '{1}'", key,val),ModuleTraceSwitch.Sw.Info);
				PDB.UpdatePortalSetting(portalSettings.PortalID, key,val);  
			}
			catch (Exception ex)
			{
				if (ModuleTraceSwitch.Sw.TraceError)
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]SiteSettings EditTable_UpdateControl ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
			}
		}

		#region Std overrides

		public override void Page_PreInit(object sender, EventArgs e)
		{
			if (ModuleTraceSwitch.Sw.TraceVerbose)
				Trace2.WriteLine("[V]SiteSettings Page_PreInit BEG", ModuleTraceSwitch.Sw.Info);
			base.Page_PreInit(sender, e);
			updateBtn.SkinID	        =	"Update_"+Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
			// We flush cache to enable correct localization of items
			PortalSettings.FlushAllPortalSettingsCache();
			try
			{
				siteName.Text           =   portalSettings.PortalName;
				sitePath.Text           =   portalSettings.PortalPath;
				TbCrmServer.Text        =   portalSettings.CrmServer.DiscoServer;
				TbCrmOrganization.Text  =   portalSettings.CrmServer.Organization;
				PortalType              =   (int)portalSettings.PortalType;
				EditTable.DataBind();
			}
			catch (Exception ex)
			{
				if (ModuleTraceSwitch.Sw.TraceError)
					Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture, "[E]SiteSettings Page_PreInit ex : {0}", ex), ModuleTraceSwitch.Sw.Info);
			}
			if (ModuleTraceSwitch.Sw.TraceVerbose)
				Trace2.WriteLine("[V]SiteSettings Page_PreInit END", ModuleTraceSwitch.Sw.Info);

		}
		
		override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
		}

		private void InitializeComponent() 
		{
			EditTable.UpdateControl     +=  new UpdateControlEventHandler(EditTable_UpdateControl);
			Load                        +=  new System.EventHandler(this.Page_Load);
			ADNUpdateModule             +=  new PortalModuleEventHandler(SiteSettings_ADNUpdateModule);
		}
		
		#endregion Std overrides
	}
}